import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log(config)
    if (store.getters.token) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 结构返回的数据，用success字段判断调用是否成功
    // 如果返回数据失败，利用element组件，提示用户
    const { msg: message } = response.data
    if (response.status === 200) {
      // console.log(response.data.success)
      return response
    // console.log(response)
      // if (success) {
      //   return response
      // } else {
      //   Message({
      //     message,
      //     type: 'error'
      //   })
      //   // 返回错误调用状态
      //   return Promise.reject(message)
      // }
    } else {
      return Promise.reject(message)
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default service
